package cn.changeforyou.demo.netty.common;

import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * Created by apple on 17/10/21.
 */
public class SSLContextFactory {

    Logger log = LoggerFactory.getLogger(SSLContextFactory.class);

    public SSLContext getServerSslContext() throws Exception {
        String passwordPath = File.separator + "srv" + File.separator + "docker" + File.separator + "others" + File.separator + "jks-password.txt";
//        String jksPath = File.separator + "srv" + File.separator + "docker" + File.separator + "others" + File.separator + "3915602__scezu.com.jks";
        String jksPath = File.separator + "srv" + File.separator + "docker" + File.separator + "others" + File.separator + "demo.jks";
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(passwordPath), CharsetUtil.UTF_8));
        String password = bufferedReader.readLine();
        bufferedReader.close();
        log.debug("加载了密码: {}", password);

        char[] passArray = password.toCharArray();
        SSLContext sslContext = SSLContext.getInstance("TLSv1");
        KeyStore ks = KeyStore.getInstance("JKS");
        //加载keytool 生成的文件
        FileInputStream inputStream = new FileInputStream(jksPath);
        ks.load(inputStream, passArray);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, passArray);
        sslContext.init(kmf.getKeyManagers(), null, null);
        inputStream.close();
        return sslContext;
    }

    public SSLContext getClientSslContext() throws Exception {
        String jksPath = File.separator + "srv" + File.separator + "docker" + File.separator + "others" + File.separator + "demo.jks";
        SSLContext sslContext = SSLContext.getInstance("TLSv1");
        KeyStore ks = KeyStore.getInstance("JKS");
        //加载keytool 生成的文件
        FileInputStream inputStream = new FileInputStream(jksPath);
        ks.load(inputStream, null);
        TrustManagerFactory tf = TrustManagerFactory.getInstance("SunX509");
        tf.init(ks);
        sslContext.init(null, tf == null ? null : tf.getTrustManagers(), null);
        inputStream.close();
        return sslContext;
    }
}
